package com.hw.shortlink.project.mq;

import com.alibaba.fastjson2.JSON;
import com.hw.shortlink.project.dto.mq.StatsMessageDto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import static com.hw.shortlink.project.common.constant.MqConstants.STATS_DIRECT_KEY;
import static com.hw.shortlink.project.common.constant.MqConstants.STATS_EXCHANGE_NAME;


@Component
@RequiredArgsConstructor
@Slf4j
public class ShortLinkStatsProducer {

    private final RabbitTemplate rabbitTemplate;

    public void SendShortLinkStatsMessage(StatsMessageDto statsMessageDto) {
        try {
            rabbitTemplate.convertAndSend(STATS_EXCHANGE_NAME,STATS_DIRECT_KEY, JSON.toJSONString(statsMessageDto),(message)->{
                message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);
                return message;
            });

        } catch (AmqpException e) {
            log.error("短链接统计发送消息到消息队列失败");
            //throw new RuntimeException(e);
        }
    }
}
